package lb.io.lblet;

import java.util.ArrayList;
import java.util.List;

public class Channel<T> {
    private final List<T> list = new ArrayList<>();

    private int size = 0;

    public Channel(int size) {
        this.size = size;
    }

    public synchronized T take() {
        while (list.size() == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        T msg = list.remove(0);
        size -= 1;
        notifyAll();
        return msg;
    }

    public synchronized void put(T msg) {
        while (list.size() >= size) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        list.add(msg);
        size += 1;
        notifyAll();
    }
}
